package hazesoft.Collection;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.io.*;
import java.text.DateFormat;
import java.util.*;

import org.xmlpull.v1.XmlSerializer;



public class Collection_Collect_Activity extends Activity {
	
	String Loc = "";
	LocationManager locationManager ;
	
	int FedtoIndex(String value)
	{
		if(value == "0")
			return 0;
		else if(value == "0.5")
			return 1;
		else if(value == "1")
			return 2;
		else if(value == "1.5")
			return 3;
		else if(value == "2")
			return 4;
		else
			return 0;
	}
	
	void PopulateCombo(Spinner combo, int Count, double Factor)
	{
		ArrayAdapter <CharSequence> adapter =
				  new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				
		for(int x = 0; x < Count; x++)
		{
			java.text.DecimalFormat df = new java.text.DecimalFormat("0.#######");
			adapter.add(df.format(x * Factor));
		}
		
		combo.setAdapter(adapter);
		
		
	}
	
	
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.collection);
        
        
        findViewById(R.id.btnGetBarcode).setOnClickListener(btnGetBarcode_OnClick);
        findViewById(R.id.button1).setOnClickListener(btnGetSiteCode_OnClick);
        findViewById(R.id.btnSwapBarcode).setOnClickListener(btnSwapScan);
        EditText edtBarcode = (EditText)findViewById(R.id.edtBarcode);
        edtBarcode.requestFocus();

        Spinner comboSupers = (Spinner)this.findViewById(R.id.comboSupers);
		Spinner comboBees = (Spinner)findViewById(R.id.comboBees);
		Spinner comboCapped = (Spinner)findViewById(R.id.comboCapped);
		Spinner comboFed = (Spinner)findViewById(R.id.comboFed);
		Spinner comboHarvested = (Spinner)findViewById(R.id.comboHarvested);
		
		PopulateCombo(comboSupers, 5, 1);
		PopulateCombo(comboBees, 45, 1);
		PopulateCombo(comboCapped, 45, 1);
		PopulateCombo(comboHarvested, 45, 1);
		PopulateCombo(comboFed, 5, 0.5);
        
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 90 * 1000, (float) 10.0, locationListener);
        
        
    }
	
	LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          Loc = location.getLongitude() + "S" + location.getLatitude();
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };
	
      @Override
      protected void onStop()
      {
    	  super.onStop();
    	 locationManager.removeUpdates(locationListener);
      }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.collect_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.mNext:
	    	try
	    	{
				SaveCurrentStats();
	    	}
	    	catch(Exception e)
	    	{
	    		MessageBox(e.toString());
	    	}
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public View.OnClickListener btnGetBarcode_OnClick = new View.OnClickListener() {
		public void onClick(View v) {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        intent.setPackage("com.google.zxing.client.android");
	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	        startActivityForResult(intent, 0);
	        
		}
	};
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	    if (requestCode == 0) {
	        if (resultCode == RESULT_OK) {
	        	EditText edit = (EditText)findViewById(R.id.edtBarcode);
	        	edit.setText(intent.getStringExtra("SCAN_RESULT"));
	            // Handle successful scan
	        } else if (resultCode == RESULT_CANCELED) {
	            // Handle cancel
	        }
	        LoadCurrentStats("");
	    }
	    else if(requestCode == 1)
	    {
	    	if (resultCode == RESULT_OK) {
	        	EditText edit = (EditText)findViewById(R.id.edtSiteName);
	        	edit.setText(intent.getStringExtra("SCAN_RESULT"));
	            // Handle successful scan
	        } else if (resultCode == RESULT_CANCELED) {
	            // Handle cancel
	        }
	    }
	    
	    else if(requestCode == 2)
	    {
	    	if (resultCode == RESULT_OK) {
	        	EditText edit = (EditText)findViewById(R.id.edtSwap);
	        	edit.setText(intent.getStringExtra("SCAN_RESULT"));
	            // Handle successful scan
	        } else if (resultCode == RESULT_CANCELED) {
	            // Handle cancel
	        }
	    }
	    
	}
	
	public View.OnClickListener btnGetSiteCode_OnClick = new View.OnClickListener() {
		public void onClick(View v) {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        intent.setPackage("com.google.zxing.client.android");
	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	        startActivityForResult(intent, 1);
	        
		}
	};
	
	public View.OnClickListener btnSwapScan = new View.OnClickListener() {
		
		public void onClick(View v) {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	        intent.setPackage("com.google.zxing.client.android");
	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	        startActivityForResult(intent, 2);
			
		}
	};
	
	
	
	private void SaveCurrentStats()
	{
		
		String state = Environment.getExternalStorageState();
		/*
		if (!Environment.MEDIA_MOUNTED.equals(state)) {
			MessageBox("No SD card Found, Cant continue!");
			//return;
		}
		*/
		
		//////////////////////////////////////////////////////////////////////////////////
		// Get All Components
		//////////////////////////////////////////////////////////////////////////////////
		EditText edtBarcode = (EditText)findViewById(R.id.edtBarcode);
		EditText edtSiteName = (EditText)findViewById(R.id.edtSiteName);
		EditText edtSwap = (EditText)findViewById(R.id.edtSwap);
		EditText edtComment = (EditText)findViewById(R.id.edtComments);
		EditText edtRain = (EditText)findViewById(R.id.edtRain);
		
		Spinner comboSupers = (Spinner)this.findViewById(R.id.comboSupers);
		Spinner comboBees = (Spinner)findViewById(R.id.comboBees);
		Spinner comboCapped = (Spinner)findViewById(R.id.comboCapped);
		Spinner comboFed = (Spinner)findViewById(R.id.comboFed);
		Spinner comboHarvested = (Spinner)findViewById(R.id.comboHarvested);
		
		CheckBox checkManipulation = (CheckBox)findViewById(R.id.chkManipulation);
		CheckBox checkDisease = (CheckBox)findViewById(R.id.chkDiseases);
		CheckBox checkQueen = (CheckBox)findViewById(R.id.chkQueen);
		
		
		
		/////////////////////////////////////////////////////////////////////////////////
		// Write Contents to File
		////////////////////////////////////////////////////////////////////////////////
		try {
				FileOutputStream outs = openFileOutput(edtBarcode.getText().toString() + ".dat", Context.MODE_WORLD_READABLE);
				OutputStreamWriter out = new OutputStreamWriter(outs);
				out.write(edtBarcode.getText().toString() + '\n');
				out.write(edtSiteName.getText().toString() + '\n');
				out.write(edtSwap.getText().toString() + '\n');
				out.write(MakeURLReady(edtComment.getText().toString()) + '\n');
				out.write(edtRain.getText().toString() + '\n');
				
			    out.write(comboSupers.getSelectedItem().toString() + "\n");
			    out.write(comboBees.getSelectedItem().toString() + "\n");
			    out.write(comboCapped.getSelectedItem().toString() + "\n");
			    out.write(Integer.toString(comboFed.getSelectedItemPosition()) + "\n");
			    out.write(comboHarvested.getSelectedItem().toString() + "\n");
			    
			    out.write(BooltoStr(checkManipulation.isChecked()) + "\n");
			    out.write(BooltoStr(checkDisease.isChecked()) + "\n");
			    out.write(BooltoStr(checkQueen.isChecked()) + "\n");
			    out.write(MakeURLReady(Loc) + "\n");
			    
			    
				out.close();
                outs.close();
		        
		} catch (IOException e) {
		    MessageBox( "Could not write file " + e.getMessage());
		}
		////////////////////////////////////////////////////////////////////////////////
		
		
		if(Loc == "")
		{
			MessageBox("Please Wait for this device to get an accurate GPS lock before continuing.");
		}
		else
		{
		////////////////////////////////////////////////////////////////////////////////
		// Clear Data and ready for next collection
		////////////////////////////////////////////////////////////////////////////////
		edtBarcode.setText("");
		edtSiteName.setText("");
		edtSwap.setText("");
		edtComment.setText("");
		
		comboSupers.setSelection(0);
		comboBees.setSelection(0);
		comboFed.setSelection(0);
		comboHarvested.setSelection(0);
		comboCapped.setSelection(0);

		checkManipulation.setChecked(false);
		checkDisease.setChecked(false);
		checkQueen.setChecked(false);
		
		edtBarcode.requestFocus();
		}
		////////////////////////////////////////////////////////////////////////////////
		
	}
	
	
	private void LoadCurrentStats(String HiveID)
	{
		int Year, Month, Day = 0;
		String state = Environment.getExternalStorageState();

		/*
		if (!Environment.MEDIA_MOUNTED.equals(state)) {
			MessageBox("No SD card Found, Cant continue!");
			//return;
		}*/
		
		try
		{
		//////////////////////////////////////////////////////////////////////////////////
		// Get All Components
		//////////////////////////////////////////////////////////////////////////////////
		EditText edtBarcode = (EditText)findViewById(R.id.edtBarcode);
		EditText edtSiteName = (EditText)findViewById(R.id.edtSiteName);
		EditText edtSwap = (EditText)findViewById(R.id.edtSwap);
		EditText edtComment = (EditText)findViewById(R.id.edtComments);
		EditText edtRain = (EditText)findViewById(R.id.edtRain);
		
		Spinner comboSupers = (Spinner)this.findViewById(R.id.comboSupers);
		Spinner comboBees = (Spinner)findViewById(R.id.comboBees);
		Spinner comboCapped = (Spinner)findViewById(R.id.comboCapped);
		Spinner comboFed = (Spinner)findViewById(R.id.comboFed);
		Spinner comboHarvested = (Spinner)findViewById(R.id.comboHarvested);
		
		CheckBox checkManipulation = (CheckBox)findViewById(R.id.chkManipulation);
		CheckBox checkDisease = (CheckBox)findViewById(R.id.chkDiseases);
		CheckBox checkQueen = (CheckBox)findViewById(R.id.chkQueen);
		

		
		try {
			FileInputStream fIn = openFileInput(edtBarcode.getText().toString() + ".dat");
			InputStreamReader in = new InputStreamReader(fIn);
			BufferedReader br = new BufferedReader(in);
			br.readLine();
		    edtSiteName.setText(br.readLine());
		    edtSwap.setText(br.readLine());
		    edtComment.setText(br.readLine());
		    edtRain.setText(br.readLine());
		    
		    comboSupers.setSelection(Integer.parseInt(br.readLine()));
		    comboBees.setSelection(Integer.parseInt(br.readLine()));
		    comboCapped.setSelection(Integer.parseInt(br.readLine()));
		    comboFed.setSelection(Integer.parseInt(br.readLine()));
		    comboHarvested.setSelection(Integer.parseInt(br.readLine()));
		    
		    checkManipulation.setChecked(StrtoBool(br.readLine()));
		    checkDisease.setChecked(StrtoBool(br.readLine()));
		    checkQueen.setChecked(StrtoBool(br.readLine()));
		    Loc = br.readLine();    
		        in.close();
		} catch (IOException e) {
		    MessageBox( "Could not read file " + e.getMessage());
		}
		
		}catch(Exception ex)
		{
			
		}
		
	}
	
	private String BooltoStr(boolean Input)
	{
		if(Input == true)
			return "true";
		else return "false";
	}
	
	private boolean StrtoBool(String Input)
	{
		//MessageBox(Input);
		if(Input.equals("true"))
			return true;
		else 
			return false;
	}
	public void MessageBox(String message){
	    Toast.makeText(this,message,Toast.LENGTH_LONG).show();
	}
	
	public String MakeURLReady(String Input)
	{
		String Output = Input.replace('.', 'P');
		Output = Output.replace( " ","%20");
		return Output.replace('-', 'N');
	}
	
	
		
}





